package com.xzy.urp.handle;


import com.xzy.urp.common.annotations.EnableLoginHandle;
import com.xzy.urp.common.exception.Assert;
import com.xzy.urp.common.result.ResponseEnum;
import com.xzy.urp.utils.JwtUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;

public class LoginHandle extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {

        // 注解判断
        HandlerMethod method = (HandlerMethod) handler;
        EnableLoginHandle loginRequired = method.getMethodAnnotation(EnableLoginHandle.class);


        if (null == loginRequired)//未开启拦截
        {

            return true;
        } else //开启拦截
        {
            int[] identity = loginRequired.identity();
            String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
            boolean result = JwtUtils.checkToken(token);
            //拦截到未登录后直接抛异常,靠mvc的异常处理器去返回错误信息,要不然没办法返回错误信息
            Assert.isTrue(result, ResponseEnum.LOGIN_AUTH_ERROR);


            Integer userIdentity = JwtUtils.getIdentity(token);
            //"用户类型（0:普通学生，1:留学生，2:教师，3:管理员）" 01都为学生权限
            AtomicBoolean b = new AtomicBoolean(false);
            Arrays.stream(identity).forEach(e->{
                if(userIdentity.equals(e)){
                     b.set(true);
                }
            });


            return b.get();





        }


    }

}
